<template>
  <div>
      <div class="logo-header">
        <img class="logo-view" src="../../assets/login/clogo1.png" />
      </div>
    <div class="login-container">
     <img class="logo-st" src="../../assets/login/001.png" />
           <img class="logo-srt" src="../../assets/login/002.png" />

      <el-form ref="loginForm" 
      :model="loginForm" 
      :rules="loginRules" 
      class="login-form" 
      autocomplete="on" 
      label-position="left">

        <div class="title-container">
          欢迎登录
        </div>
        <el-form-item prop="username">
          <span class="svg-container">
            <svg-icon icon-class="user" />
          </span>
          <el-input
            ref="username"
            v-model="loginForm.username"
            placeholder="请输入登录账户"
            name="username"
            type="text"
            tabindex="1"
            autocomplete="on"
          />
        </el-form-item>

        <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="请输入登录密码"
              name="password"
              tabindex="2"
              autocomplete="on"
              @keyup.native="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter.native="handleLogin"
            />
            <!-- <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span> -->
          </el-form-item>
        </el-tooltip>
        <div>
            <el-button :loading="loading" type="primary" class="btn-login"
          @click.native.prevent="handleLogin">登录</el-button>
        </div>
        <div>
          <el-button  type="primary" class="btn-wxlogin" @click="btnOpenWX">
            <div class="wxlogin">
              <svg xmlns="http://www.w3.org/2000/svg" 
                fill="#30ab74"  viewBox="0 0 32 32" width="24" height="24">
              <g>
              <path d="M27.261 24.632l0.475-0.419c1.2-1.061 1.867-2.427 1.867-3.864 0-3.112-3.147-5.74-7.133-5.74s-7.136 2.627-7.136 5.74c0 3.112 3.147 5.741 7.133 5.741 0.006 0 0.013 0 0.021 0 0.904 0 1.775-0.139 2.593-0.398l-0.061 0.017 0.507-0.157 1.804 0.889-0.069-1.807zM28.749 28.628l-3.333-1.64c-0.875 0.279-1.882 0.44-2.926 0.44-0.007 0-0.014 0-0.022-0h0.001c-4.683-0.005-8.469-3.175-8.469-7.081s3.791-7.071 8.467-7.071c4.68 0 8.467 3.167 8.467 7.073 0 1.884-0.88 3.596-2.316 4.863l0.133 3.413zM20.727 18.792c0 0.736-0.622 1.333-1.389 1.333s-1.389-0.597-1.389-1.333c0-0.736 0.622-1.333 1.389-1.333s1.389 0.597 1.389 1.333zM27.411 18.792c0 0.736-0.622 1.333-1.389 1.333s-1.389-0.597-1.389-1.333c0-0.736 0.622-1.333 1.389-1.333s1.389 0.597 1.389 1.333zM11.423 19.467c0-4.333 3.893-7.901 8.96-8.493-0.933-3.343-4.569-5.821-8.871-5.821-5.053 0-9.107 3.396-9.107 7.52 0 2.2 1.157 4.259 3.147 5.684l0.32 0.231-0.203 1.729 2.072-0.793 0.231 0.080c1.038 0.373 2.235 0.589 3.483 0.591h0.001c-0.023-0.215-0.036-0.465-0.036-0.717 0-0.003 0-0.007 0-0.010v0zM1.073 12.672c0-4.92 4.697-8.853 10.44-8.853 5.217 0 9.64 3.267 10.341 7.651l0.12 0.731-0.74 0.040c-4.784 0.263-8.476 3.447-8.476 7.227 0 0.416 0.044 0.827 0.131 1.231l0.164 0.76-0.773 0.047c-0.237 0.017-0.514 0.026-0.793 0.026-1.329 0-2.608-0.214-3.805-0.611l0.085 0.024-3.683 1.409 0.373-3.147c-2.133-1.664-3.384-4.008-3.384-6.537zM16.267 10.267c0 0.736-0.597 1.333-1.333 1.333s-1.333-0.597-1.333-1.333c0-0.736 0.597-1.333 1.333-1.333s1.333 0.597 1.333 1.333zM9.467 10.267c0 0.736-0.597 1.333-1.333 1.333s-1.333-0.597-1.333-1.333c0-0.736 0.597-1.333 1.333-1.333s1.333 0.597 1.333 1.333z"></path></g></svg>
            微信扫码登录
            </div>
            </el-button>
        </div>
        <div class="forget-pass" @click="openForget">
          忘记密码?
        </div>
      </el-form>

    </div>
     <el-dialog
        title=""
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        :before-close="wxClose"
        destroy-on-close
        width="500px">
        <div style="position:relative;">
            <div class="wx-pupop-title">请使用手机微信扫描二维码，绑定手机号，安全便捷登录</div>
            <div class="wx-pupop-image" id="login_container" style="height:400px;width: 400px;margin: 0 auto;">
              <div style="font-size:13px;padding-top:200px">加载中...</div>
            </div>
            <div class="loginsucces" v-if="wxLoginType">
              <div class="texts">登录成功</div>
            </div>
      </div>
      </el-dialog>
       <el-dialog
        title="忘记密码"
        :visible.sync="forgetVisible"
        :close-on-click-modal="false"
        width="400px">
          <div v-if="showType===1" style="padding:10px">
          <el-input v-model="forgetForm.phone" maxlength="11" style="width:350px" placeholder="请输入手机号"></el-input>
            <el-input placeholder="请输入验证码" maxlength="6" style="width:350px;margin-top:20px" v-model="forgetForm.code">
              <template slot="append"><div style="cursor:pointer;" :style="{color:codeDisabled?'#30ab74':'#888'}"  @click="btnSend('FINDPASSWORD')">{{codeMsg}}</div> </template>
            </el-input>
             <el-button  type="primary" class="btn-next"  @click="btnNext">下一步</el-button>
            </div>

             <div v-else  style="padding:10px">
                <el-input v-model="forgetForm.newpassword" type="password" maxlength="24" style="width:350px" placeholder="请输入密码"></el-input>
                <el-input placeholder="请输入确认密码" type="password" maxlength="24" style="width:350px;margin-top:20px" v-model="forgetForm.password">
                </el-input>
                <el-button  type="primary" class="btn-next"  @click="btnConfim">确定</el-button>
            </div>
      </el-dialog>

             <el-dialog
        title="绑定手机号"
        :visible.sync="phoneVisible"
        :close-on-click-modal="false"
        width="400px">
          <div style="padding:10px">
            <div style="font-size:13px"> <i class="el-icon-check" style="color:#30ab74" /> 绑定手机号后可便捷安全登录</div>
             <div style="font-size:13px;padding:10px 0 30px 0"><i class="el-icon-check" style="color:#30ab74" /> 如果您是老用户我们将为您同步创建课件</div>
           <el-input v-model="forgetForm.phone" maxlength="11" style="width:350px" placeholder="请输入手机号"></el-input>
            <el-input placeholder="请输入验证码" maxlength="6" style="width:350px;margin-top:20px" v-model="forgetForm.code">
              <template slot="append"><div style="cursor:pointer;" :style="{color:codeDisabled?'#30ab74':'#888'}"  @click="btnSend('BINDPHONE')">{{codeMsg}}</div> </template>
            </el-input>
             <el-button  type="primary" class="btn-next"  @click="btnCodePhone">提交</el-button>
          </div>
      </el-dialog>

        <div class="footer-view">
          <div style="padding-bottom:15px">版权归：重庆探程数字科技有限公司</div>
          <div>
             <span>网站:<a href="http://www.cqtancheng.com" target="_blank">www.cqtancheng.com</a>  </span>
            <span> 电话：023-63615762     </span>
             <span> 网站备案：<a target="_blank" href="https://beian.miit.gov.cn/state/outPortal/loginPortal.action">渝ICP备2020014689号-1</a>  </span>
             
             </div>
        </div>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import { removeToken } from '@/utils/auth'
import Cookies from 'js-cookie'
import {sendCode,verifyCode,changePSW,getToken,refreshToken,getPhone,sendWxSmsCode,bindPhone,wxLogin} from '@/api/clientManage'
import { clearInterval } from 'timers';

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入登录账户'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入登录密码'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        loginType:'teacher'
      },
      forgetForm:{
        phone:'',
        code:'',
        password:'',
        newpassword:''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      dialogVisible: false,
      forgetVisible:false,
      redirect: undefined,
      otherQuery: {},
      showType:1,
        // 是否禁用按钮
      codeDisabled: true,
      phoneVisible:false,
      // 倒计时秒数
      countdown: 60,
      // 按钮上的文字
      codeMsg: '获取验证码',
      // 定时器
      timer: null,
      loginTimer:null,
      xwInfo:null,
      wxLoginType:false
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    removeToken()  
    if(this.getQueryValue('code') &&this.$route.query?.logout!=1){
      //获取微信信息 openId 
      getToken({
        code:this.getQueryValue('code')
      }).then((res)=>{
         if(res.code==0){
             this.xwInfo = res.data ||null
              //判断是否存在手机号
              getPhone({
                  code:this.getQueryValue('code'),
                  openid: this.xwInfo.openid,
                  accessToken: this.xwInfo.access_token, 
                }).then((res)=>{
                  if(res.code && !res.success){
                      this.phoneVisible = true
                  }else{
                    this.goWxLogin({
                        openid: this.xwInfo.openid,
                        phone: this.xwInfo.phone
                    })
                  }
           })
         }
      })

    }

  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  methods: {
     getQueryValue(queryName) {
        var reg = new RegExp("(^|&)" + queryName + "=([^&]*)(&|$)", "i");
        // 获取url中"?"符后的字符串并正则匹配
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return decodeURI(r[2]);
        } else {
            return null;
        }
    },
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    goWxLogin(data){
         wxLogin(data).then((wx)=>{
            if(wx){
              this.wxLoginType = true
              this.$message.success("登录成功");
              setTimeout(() => {
                localStorage.setItem('getName',wx?.userName)
                localStorage.setItem('info-teacher',JSON.stringify(wx))
                this.$store.dispatch('app/openSideBar', { withoutAnimation: true })
                localStorage.setItem('menuKey',9)
                this.$router.push({ path: '/clientManage/courseware', query: this.otherQuery }) 
              }, 2000);
            }else{
              this.$message.error("登录失败，请重新扫码登录!");
            }
        })
    },
    btnCodePhone(){
     if(!this.forgetForm.phone ||  this.forgetForm.phone.length<11){
        this.$message.error("请输入正确的手机号");
        return
      }
       if(!this.forgetForm.code ||  this.forgetForm.code.length<6){
        this.$message.error("请输入正确的验证码");
        return
      }
      bindPhone({
        phone: this.forgetForm.phone,
        phoneCode: this.forgetForm.code,
        weChatCode:this.xwInfo.openid
      }).then((res)=>{
        if(res.code===0){
              this.goWxLogin(
                {
                  phone: this.forgetForm.phone,
                  openid:this.xwInfo.openid
              })
        }else{
          this.$message.error(res.message||"操作失败");
        }
      })
    },
    btnOpenWX(){
      this.dialogVisible = true
      setTimeout(() => {
        new WxLogin({
          self_redirect:false,
          response_type:'code',
          id:"login_container", 
          appid:"wx8b81e9dabdcea435",
          scope: "snsapi_login", 
          redirect_uri: encodeURIComponent(`${window.location.origin}/teacher/`),
          state: "", 
          style: "black",
          href: ""
        });
      }, 500);
      
    },
    wxClose(){
      this.dialogVisible = false
    },
    getCode() {
      // 验证码60秒倒计时
      if (!this.timer) {
          this.timer = setInterval(() => {
          if (this.countdown > 0 && this.countdown <= 60) {
            this.countdown--;
            if (this.countdown !== 0) {
              this.codeMsg = "重新发送(" + this.countdown + ")";
              this.codeDisabled = false;
            } else {
              clearInterval(this.timer);
              this.codeMsg = "获取验证码";
              this.countdown = 60;
              this.timer = null;
              this.codeDisabled = true;
            }
          }
      }, 1000)
      }
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm)
            .then((res) => {
              if(res.success){
                this.$store.dispatch('app/openSideBar', { withoutAnimation: true })
                localStorage.setItem('menuKey',9)
                this.$router.push({ path: '/clientManage/courseware', query: this.otherQuery })
              }else{
                this.$message.error(res.message||"操作失败");
              }
              this.loading = false 
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    openForget(){
      this.showType = 1
      this.forgetVisible = true
    },

    btnConfim(){
      if(!this.forgetForm.newpassword ||  this.forgetForm.password.newpassword<6){
        this.$message.error("请输入大于六位数的密码");
        return
      }
       if(this.forgetForm.newpassword!=this.forgetForm.password){
        this.$message.error("两次密码不一致");
        return
      }
       changePSW({
        newPassword: this.forgetForm.password,
        phone: this.forgetForm.phone
      }).then((res)=>{
        if(res.code===0){
          this.forgetVisible = false
          this.$message.success("密码修改成功");
        }else{
          this.$message.error(res.message||"操作失败");
        }
      })
    },
    btnSend(type){
      if(!this.forgetForm.phone ||  this.forgetForm.phone.length<11){
        this.$message.error("请输入正确的手机号");
        return
      }
      if(!this.codeDisabled){
        return
      }
      sendCode({
        bizTypeName:type,
        phone: this.forgetForm.phone
      }).then((res)=>{
        if(res.code===0){
          this.$message.success("验证码已发送请注意查收!");
          this.codeDisabled =false
          this.getCode()
        }else{
          this.$message.error(res.message||"操作失败");
        }
      })
    },
     btnNext(){
      if(!this.forgetForm.phone ||  this.forgetForm.phone.length<11){
        this.$message.error("请输入正确的手机号");
        return
      }
      if(!this.forgetForm.code ||  this.forgetForm.phone.code<6){
        this.$message.error("请输入正确的验证码");
        return
      }
      verifyCode({
        bizTypeName: "FINDPASSWORD",
        phone: this.forgetForm.phone,
        smsCode: this.forgetForm.code,
      }).then((res)=>{
        if(res.code===0){
          this.showType=2
        }else{
          this.$message.error(res.message||"操作失败");
        }
      })
     
    },
  }
}
</script>

<style lang="scss">
.login-container {
  background-image: url('../../assets/login/login-bg.jpg');
  background-position: top;
  background-size: cover;
  .el-input {
    display: inline-block;
    height: 45px;
    line-height: 45px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
    }
  }
  .el-form-item {
    background: #f5f5f5;
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;
.dialog-fade-enter-active {
  animation: anim-open .5s !important;
}
@keyframes anim-open {
  0%{
    opacity: 0;
    transform:translateY(300px)
  }
    100%{
    opacity: 1;
    transform:translateY(0)
  }
}
.dialog-fade-leave-active {
   animation: anim-close 1s !important;
}
@keyframes anim-close {
  0%{
    opacity: 1;
    transform:translateY(0)
  }
    100%{
    opacity: 0;
    transform:translateY(300px)
  }
}
.logo-st{
    height: 500px;
    position: absolute;
    top: 50%;
    margin-top: -250px;
    z-index: 1;
    left: 10%; 
}
.logo-srt{
    height: 500px;
    position: absolute;
    top: 50%;
    margin-top: -250px;
    z-index: 1;
    right: 10%; 
}
.wx-pupop-title{
    font-size: 15px;
    text-align: center;
    color: #424242;
    padding: 20px 0;
}
.wx-pupop-image{
  text-align: center;
    width: 100%;
    padding-bottom:20px;
    img{
      width:80%;
    }
}
  .logo-header{
    height:70px;
    margin:0;
    background-color: #fff;
    box-shadow: rgba(145, 145, 145, 0.17) 0px 3px 6px 0px;
    width:100%;
    position: relative;
      .logo-view{
        height:50px;
        position: absolute;
        left:20px;
        top:50%;
        margin-top:-25px;
      }
  }
  .loginsucces{
    font-size: 13px;
    padding-top: 200px;
    position: absolute;
    height: 280px;
    width: 280px;
    bottom: 72px;
    left: 50%;
    margin-left: -140px;
    background-color: #31c784eb;
    text-align: center;
    color: #30ab74;
    .texts{
      position: absolute;
      width: 100%;
      text-align: center;
      top: 120px;
      font-size: 24px;
      color: #fff;
    }
  }
.login-container {
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  position: relative;
  height: calc(100vh - 170px);
  min-width:1000px;
  min-height:calc(100vh - 170px);
  .center-login{
    width:500px;
    height:100px;
    text-align: center;
    margin:0 auto;
    position: absolute;
    left:50%;
    margin-left:-250px;
    top:160px;
    display: flex;
    justify-content: space-between;
    img{
      height:63px;
      width:228px;
    }
  }
  .login-form {
    position: absolute;
    width: 400px;
    height:450px;
    margin: 0 auto;
    overflow: hidden;
    background-color: #fff;
    right:15%;
    top:50%;
    margin-top:-220px;
    padding:30px;
    border-radius:6px;
    z-index:9;
  }
.btn-login{
    width: 100%;
    margin-bottom: 20px;
    margin-top: 10px;
    background-color: #30ab74 !important;
    border-color: #30ab74 !important;
    height: 40px;
}
.btn-wxlogin{
    width: 100%;
    margin-bottom:10px;
    margin-top: 0;
    background-color: #fff !important;
    border-color: #30ab74 !important;
    color:#30ab74 !important;
    height: 40px;
    .wxlogin{
          display: flex;
        justify-content: center;
        align-items: center;
    }
}

.forget-pass{
      text-align: center;
    font-size: 13px;
    color: #888;
    padding-top: 10px;
    cursor: pointer;
}

  .tip-view{
    font-size:14px;
    color:#565656;
    line-height:25px;
    position: relative;
    .down{
      position: absolute;
      font-size:14px;
      right:0;
      color:#0777df;
      font-weight: bold;
      bottom:0;
      text-decoration:underline
    }
  }
  .svg-container {
    padding: 0 5px 0 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }
  .title-container {
    position: relative;
    font-size: 20px;
    color: #30ab74;
    margin: 0px auto 40px auto;
    text-align: left;
    font-weight: bold;
    border-bottom:1px solid #30ab74;
    line-height: 50px;
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 2px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }
  .el-button--primary {
      color: #FFFFFF;
      background-color: #0777df;
      border-color: #1890ff;
  }
  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }

}
.btn-next{
      width: 100%;
    margin-bottom: 20px;
    margin-top: 30px;
    background-color: #30ab74 !important;
    border-color: #30ab74 !important;
    height: 40px;
}
  .footer-view{
    background-color: #2e2e41;
    height: 100px;
    width: 100%;
    text-align: center;
    color: #fff;
    font-size: 15px;
    padding-top:30px;
    span{
      padding:0 10px;
    }
  }
</style>
